#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "r_socket_common.h"

#include "r_socket_ipv4_tcp_client.h"
#include "r_socket_obj_manager.h"

#include "utilities/string_operator.h"
#include "utilities/r_logger.h"

namespace eniac
{

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::set_socket_property(const r_socket::ptr socket_obj, r_socket_property_type type, void* property, size_t property_size)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (type == r_socket_property_type::SOCKET_PROPERTY_OWN_ADDRESS)
    {
        return set_socket_own_address(socket_obj, property, property_size);
    }

    if (type == r_socket_property_type::SOCKET_PROPERTY_OWN_PORT_NUMBER)
    {
        return set_socket_own_port(socket_obj, property, property_size);
    }

    if (type == r_socket_property_type::SOCKET_PROPERTY_SERVER_ADDRESS)
    {
        return set_socket_server_address(socket_obj, property, property_size);
    }

    if (type == r_socket_property_type::SOCKET_PROPERTY_SERVER_PORT_NUMBER)
    {
        return set_socket_server_port(socket_obj, property, property_size);
    }

    return r_socket_proxy_ret_t::INVALID_PROPERTY_TYPE_FOR_THE_SOCKET;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::start_socket(const r_socket::ptr socket_obj)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (socket_obj->m_socket_fd != INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::SOCKET_FD_HAS_BEEN_SET;
    }

    if (socket_obj->m_server_address.empty())
    {
        return r_socket_proxy_ret_t::SERVER_ADDRESS_HAS_NOT_BEEN_SET_YET;
    }

    if (socket_obj->m_server_port == INVALID_SOCKET_PORT)
    {
        return r_socket_proxy_ret_t::SERVER_PORT_HAS_NOT_BEEN_SET_YET;
    }

    uint32_t self_int_addr = INADDR_ANY;
    if (!socket_obj->m_own_address.empty())
    {
        self_int_addr = ipv4_to_net_int(socket_obj->m_own_address);
    }
    int16_t self_port = INVALID_SOCKET_PORT;
    if (!socket_obj->m_own_port != INVALID_SOCKET_PORT)
    {
        self_port = socket_obj->m_own_port;
    }
    else
    {
        self_port = 0;
    }

    struct sockaddr_in self_addr;
    memset(&self_addr, 0, sizeof(self_addr));
    self_addr.sin_family = AF_INET;
    self_addr.sin_port = htons(self_port);
    self_addr.sin_addr.s_addr = self_int_addr;

    if ((socket_obj->m_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        socket_obj->m_socket_fd = INVALID_SOCKET_FD;
        r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
        return r_socket_proxy_ret_t::TO_CREATE_SOCKET_FD_IS_FAILED;
    }

    if (bind(socket_obj->m_socket_fd, (struct sockaddr*)&self_addr, sizeof(self_addr)) < 0)
    {
        close(socket_obj->m_socket_fd);
        socket_obj->m_socket_fd = INVALID_SOCKET_FD;
        r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
        return r_socket_proxy_ret_t::TO_BIND_ADDRESS_TO_FD_IS_FAILED;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = ipv4_to_net_int(socket_obj->m_server_address);
    server_addr.sin_port = htons(socket_obj->m_server_port);

    if (connect(socket_obj->m_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
    {
        close(socket_obj->m_socket_fd);
        socket_obj->m_socket_fd = INVALID_SOCKET_FD;
        r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
        return r_socket_proxy_ret_t::TO_CONNECT_SERVER_IS_FAILED;
    }

    socket_obj->m_status = r_socket_status_t::R_SOCKET_STATUS_STARTED;
    r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::read_message(const r_socket::ptr socket_obj, r_socket_message::ptr& message)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::INVALID_SOCKET_FD;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    uint64_t readable_bytes = r_socket_common::get_readable_bytes_length(socket_obj->m_socket_fd);
    if (0 == readable_bytes)
    {
        return r_socket_proxy_ret_t::NO_DATA_CAN_BE_READ;
    }

    message = r_socket_message::create_obj();
    message->m_socket_id = socket_obj->m_socket_id;
    message->m_payload.resize(readable_bytes);

    ssize_t valread = read(socket_obj->m_socket_fd, message->m_payload.data(), message->m_payload.size());
    if (valread <= 0)
    {
        message.reset();
        return r_socket_proxy_ret_t::TO_READ_DATA_FROME_SOCKET_IS_FAILED;
    }

    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::send_message(const r_socket::ptr socket_obj, const std::vector<uint8_t>& message)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::INVALID_SOCKET_FD;
    }

    if (0 == message.size())
    {
        return r_socket_proxy_ret_t::NO_DATA_CAN_BE_SENT;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    ssize_t send_num = write(socket_obj->m_socket_fd, message.data(), message.size());
    if (send_num != message.size())
    {
        //TODO Make Sure ALL Data is sent
        return r_socket_proxy_ret_t::TO_SEND_DATA_IS_FAILED;
    }

    LOG_DBG() << "To send Message is success";
    return r_socket_proxy_ret_t::OK;
}

void r_socket_ipv4_tcp_client::close_socket(const r_socket::ptr socket_obj)
{
    if (nullptr == socket_obj.get())
    {
        return;
    }

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    close(socket_obj->m_socket_fd);
    socket_obj->m_socket_fd = INVALID_SOCKET_FD;
    socket_obj->m_status = r_socket_status_t::R_SOCKET_STATUS_STOPPING;
    r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::set_socket_own_address(const r_socket::ptr socket, void* property, size_t property_size)
{
    if ( property_size < strlen("0.0.0.0") ||
         property_size > strlen("000.000.000.000") )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    std::string ip_str = reinterpret_cast<char*>(property);

    if (false == is_valid_ipv4_ip(ip_str) )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_own_address = ip_str;

    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::set_socket_own_port(const r_socket::ptr socket, void* property, size_t property_size)
{
    if (property_size != sizeof(socket->m_own_port))
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    if (INVALID_SOCKET_PORT == *reinterpret_cast<uint16_t*>(property))
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_own_port = *reinterpret_cast<uint16_t*>(property);

    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::set_socket_server_address(const r_socket::ptr socket, void* property, size_t property_size)
{
    if ( property_size < strlen("0.0.0.0") ||
         property_size > strlen("000.000.000.000") )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    std::string ip_str = reinterpret_cast<char*>(property);

    if (false == is_valid_ipv4_ip(ip_str) )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_server_address = ip_str;

    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_ipv4_tcp_client::set_socket_server_port(const r_socket::ptr socket, void* property, size_t property_size)
{
    if (property_size != sizeof(socket->m_own_port))
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    if (INVALID_SOCKET_PORT == *reinterpret_cast<uint16_t*>(property))
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_server_port = *reinterpret_cast<uint16_t*>(property);

    return r_socket_proxy_ret_t::OK;
}


}